package org.zjt.mock.demo.mock.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.RequestFacade;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.zjt.mock.demo.mock.annotation.RequestParam2;

import java.time.LocalDateTime;
import java.util.Locale;
import java.util.Objects;

/**
 * Description:  自定义controller参数类型、参数注解的处理
 *
 * @author juntao.zhang
 * Date: 2018-06-21 下午6:53
 * @see
 */
@Slf4j
public class CustomizedHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private final LocalDateTimeFormatter localDateTimeFormatter = new LocalDateTimeFormatter();
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestParam2.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        log.info("---------------------");
        Class<?> parameterType = parameter.getParameterType();
        RequestParam2 parameterAnnotation = parameter.getParameterAnnotation(RequestParam2.class);
        String parameterName = StringUtils.isEmpty(parameterAnnotation.name()) ? parameterAnnotation.value() : parameterAnnotation.name();
        parameterName = StringUtils.isEmpty(parameterName) ? parameter.getParameterName() : parameterName;
        RequestFacade requestFacade = webRequest.getNativeRequest(RequestFacade.class);
        String parameterValue = requestFacade.getParameter(parameterName);
        if (Objects.equals(parameterType,LocalDateTime.class)){
            LocalDateTime localDateTime = localDateTimeFormatter.parse(parameterValue, Locale.getDefault());
            return localDateTime;
        }
        Object parseObject = JSON.parseObject(parameterValue, parameterType);
        return parseObject;
    }
}
